import { defineStore } from "pinia";
import { ref } from "vue";
import { useTask } from "@/utils/message";
import { back } from "@/utils/index";
import { validationMobile } from "@/utils/validation";
import {
    getLoginMobileApi,
    getWechatDecryptApi,
    loginApi,
    getUserInfoApi,
    bindUserMonbileApi,
    accLoginApi,
    codeLoginApi,
    editUserInfoApi,
    updateMobileApi,
    setPaywordApi,
    setLoginPsdApi
} from "@/api/user";
import { getwxLoginParams } from "@/utils/login";
import { useCartStore } from "@/store/module/cart";

export const useMemberStore = defineStore("member", () => {
    const userInfo = ref<AnyObject>({}); // 用户信息
    const wxLoginParmas = ref<AnyObject>({}); // 微信用户信息
    const inviter = ref<string>("");

    // 获取用户信息
    const setUserInfo = async (userinfo?: AnyObject) => {
        if (userinfo) {
            userInfo.value = userinfo;
        } else {
            const token = uni.getStorageSync("token");
            if (!token && userInfo.value) {
                useTask("登录失效");
                clearUserInfo();
                return;
            }

            if (token) {
                const res: AnyObject = await getUserInfoApi({ token });
                if (!res.data.userid) {
                    clearUserInfo();
                    return;
                }
              userInfo.value = res.data;
              const cartStore = useCartStore();
              cartStore.getCartList();
            }
        }
    };

    //退出登陆
    const clearUserInfo = () => {
        userInfo.value = {};
        uni.removeStorageSync("token");
        uni.redirectTo({ url: "/pages/user/login" });
    };

    // 解密code 获取open_id
    const decipheringWxLoginCode = async () => {
        const loginRes: UniApp.LoginRes = await getwxLoginParams("weixin");
        const res: AnyObject = await getWechatDecryptApi({
            code: loginRes.code
        });
        if (res.code == 200) {
            wxLoginParmas.value = res.data;
        } else {
            console.log("获取微信用户信息失败");
            wxLoginParmas.value = {};
        }
    };

    // 微信登陆
    const wxLogin = async (e: any) => {
        let loginParams: AnyObject = {};
        let getMobile: AnyObject = {};
        if (e.target.errMsg !== "getPhoneNumber:ok") {
            useTask("您拒绝了授权!");
            return;
        }
        // 解密获取手机号码
        getMobile = await getLoginMobileApi({
            code: e.detail.code,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            username: userInfo.value?.username || undefined,
            sessionKey: wxLoginParmas.value?.session_key
        });

        // 注册登陆所需参数
        loginParams = {
            wxapp_openid: wxLoginParmas.value.openid,
            mobile: getMobile.data?.phoneNumber || undefined,
            inviter: inviter.value || undefined,
            nickname: userInfo.value?.truename || "微信用户"
        };
        uni.showLoading({ title: "登录中", mask: true });
        const res: AnyObject = await loginApi(loginParams);
        uni.hideLoading();
        if (!res.data?.userid) {
            useTask("登陆失败");
            return;
        }

        uni.setStorageSync("token", res.data.token);
        await setUserInfo(res.data);

        if (!userInfo.value.mobile) {
            await bindUserMonbileApi({ mobile: getMobile.data?.phoneNumber, username: userInfo.value.username });
            await setUserInfo();
        }

        back();
    };

    // 验证码登陆
    const codeLogin = async (user: AnyObject) => {
        if (!user.code) {
            useTask("请输入验证码");
            return;
        }
        const res: AnyObject = await codeLoginApi({
            ...user,
            inviter: inviter.value || undefined
        });

        if (res.code == 200) {
            uni.setStorageSync("token", res.data.token);
            await setUserInfo(res.data);
            back();
        } else {
            useTask(res.msg);
        }
    };

    // 账号密码登陆
    const accountLogin = async (user: AnyObject) => {
        if (!user.account) {
            useTask("请输入账号");
            return;
        }

        if (!user.password) {
            useTask("请输入密码");
            return;
        }

        if (!validationMobile(user.account)) {
            useTask("请输入正确的手机号码");
            return;
        }

        const res: AnyObject = await accLoginApi({
            ...user,
            inviter: inviter.value || undefined
        });

        if (res.code == 200) {
            uni.setStorageSync("token", res.data.token);
            await setUserInfo(res.data);
            back();
        } else {
            useTask(res.msg);
        }
    };

    // 修改用户信息
    const editUserInfo = async (user: AnyObject) => {
        const res: AnyObject = await editUserInfoApi(user);
        if (res.code == 200) {
            await setUserInfo();
            useTask("修改成功");
        } else {
            useTask(res.msg);
        }
    };

    // 修改手机号
    const setMobile = async (mobile: AnyObject) => {
        const res: AnyObject = await updateMobileApi(mobile);
        if (res.code == 200) {
            useTask("修改成功");
            await setUserInfo();
            setTimeout(() => {
                back();
            }, 500);
        } else {
            useTask(res.msg);
        }
    };

    // 重置密码
    const resetPsd = async (type: "login" | "pay", info: AnyObject) => {
        let res: AnyObject = {};
        if (type == "login") {
            res = await setLoginPsdApi(info);
            if (res.code == 200) {
                useTask("密码重置成功，请重新登陆");
                await setUserInfo();
            } else {
                useTask(res.msg);
            }
        }
        if (type == "pay") {
            res = await setPaywordApi(info);
            if (res.code == 200) {
                useTask("修改成功");
                await setUserInfo();
                setTimeout(() => {
                    back();
                }, 500);
            } else {
                useTask(res.msg);
            }
        }
    };

    return {
        userInfo,
        setUserInfo,
        clearUserInfo,
        decipheringWxLoginCode,
        wxLogin,
        codeLogin,
        accountLogin,
        editUserInfo,
        setMobile,
        resetPsd
    };
});
